import { Component, ElementRef, HostListener, OnInit, ViewChild , AfterViewInit} from '@angular/core';
import {FetchService} from "../../../../core/net/fetch.service";
import {UtilService} from "../../../../core/util/util.service";
import {NzInputDirective, NzMessageService} from "ng-zorro-antd";
import * as _ from 'lodash';
import * as moment from 'moment';
import { ActivatedRoute, Router } from '@angular/router';
import { NzNotificationService } from 'ng-zorro-antd/notification';
import { DispatchPlanService } from '../../dispatch-plan.service';
import { concatMap } from 'rxjs/operators';

const monthHead31 = ['01日', '02日', '03日', '04日', '05日', '06日', '07日', '08日', '09日', '10日', '11日', '12日', '13日', '14日', '15日', '16日', '17日', '18日', '19日', '20日', '21日', '22日', '23日', '24日', '25日', '26日', '27日', '28日', '29日', '30日', '31日'];

const monthHead30 = ['01日', '02日', '03日', '04日', '05日', '06日', '07日', '08日', '09日', '10日', '11日', '12日', '13日', '14日', '15日', '16日', '17日', '18日', '19日', '20日', '21日', '22日', '23日', '24日', '25日', '26日', '27日', '28日', '29日', '30日'];

@Component({
  selector: 'app-slt-dispatch-plan-detail',
  templateUrl: './slt-dispatch-plan-detail.component.html',
  styleUrls: ['./slt-dispatch-plan-detail.component.scss']
})
export class SltDispatchPlanDetailComponent implements OnInit, AfterViewInit {
  widthConfig = ['150px', '80px', '80px', '80px', '80px', '80px', '80px', '80px', '80px', '80px', '80px', '80px', '80px', '80px', '80px', '80px', '80px', '80px', '80px'];
  scrollConfig =  {
      x: '1590px', y: '400px'
  };
  loading = true;
  xunHead = {
    'F': ['01日', '02日', '03日', '04日', '05日', '06日', '07日', '08日', '09日', '10日'],
    'S': ['11日', '12日', '13日', '14日', '15日', '16日', '17日', '18日', '19日', '20日'],
    'T': ['21日', '22日', '23日', '24日', '25日', '26日', '27日', '28日', '29日', '30日', '31日']
  };
  pageType: string;
  state = '0';
  planName: "";
  monthReportType = "month";
  paramsData = {
    reportId: 5,
    m: "0",
    y: "2020",
    dataType: "",
  };

  keyList = []; // 数据 数值属性 列表
  hwPlanData = 0; // 黄委会计划指标
  yearOnYear = 0; // 对比
  dateHeadList = []; // 日期对象
  currentIndex = 0; // 当前选中日期 在 manageDataList中的索引
  colNameList = []; // 表头

  manageDataList = [[]];  // 管理处 上报数据
  argThreeYearsList = [[]] ; // 三年平均 数据
  valList = []; // 中心 下发 数据
  valTotalList = []; // 流量合计
  argDayList = []; // 平均日流量
  waterTotalList = []; // 水量合计

  editCache: { [key: string]: { edit: boolean; data: any } } = {};

  @ViewChild(NzInputDirective, { static: false, read: ElementRef }) inputElement: ElementRef;
  @ViewChild('wrap') wrapElement: ElementRef;
  @HostListener('window:click', ['$event'])
  handleClick(e: MouseEvent): void {
      if (this.inputElement && e.target['tagName'] !== 'INPUT') {
          Object.keys(this.editCache).forEach(key => {
              this.editCache[key].edit = null;
          });
          this.calcTableData();
      }
  }
  constructor(
    private fetchService: FetchService,
    public util: UtilService,
    private message: NzMessageService,
    private routerInfo: ActivatedRoute,
    private router: Router,
    private notification: NzNotificationService,
    public dispatchService: DispatchPlanService,
  ) {
    this.state = this.routerInfo.snapshot.queryParams['state'];
    this.pageType = this.routerInfo.snapshot.queryParams['pageType'];
    this.paramsData = Object.assign(this.paramsData, JSON.parse(this.routerInfo.snapshot.queryParams['paramsData']));
    this.planName = this.routerInfo.snapshot.queryParams['planName'];
    this.monthReportType = this.dispatchService.getMngReportTableType(this.paramsData.m).type;
    this.initDateHeader();
  }

  ngOnInit(): void {
    this.getEditableTableData();

  }
  ngAfterViewInit() {
    this.scrollConfig.y = (this.wrapElement.nativeElement.offsetHeight - 470) + 'px';
  }

  getEditableTableData() {
    this.fetchService.post<any>('plan/wrsReportData/query', this.paramsData).subscribe(res => {
      this.loading = false;
      if (this.monthReportType === 'winter') { // 冬灌
          this.getWinterMonthData(res);
      } else if (this.monthReportType === 'month') { // 月
          this.getMonthDetailData(res);
      } else { // 旬
          this.getTenDaysDetailData(res);
      }


      this.dealTableData(res);
    });
  }

  // 初始化当前时间数组
  initDateHeader() {
    const m = this.paramsData.m;
    const y = this.paramsData.y;
    if (m === '4' || m === '6') {
        this.xunHead['T'] = ['21日', '22日', '23日', '24日', '25日', '26日', '27日', '28日', '29日', '30日'];
    } else {
        this.xunHead['T'] = ['21日', '22日', '23日', '24日', '25日', '26日', '27日', '28日', '29日', '30日', '31日'];
    }
    if (m === '9') {
        this.dateHeadList = monthHead30;
    } else if (['F', 'S', 'T'].includes(this.paramsData.dataType)) {
        this.dateHeadList = this.xunHead[this.paramsData.dataType];
    } else {
        this.dateHeadList = monthHead31;
    }
  }

  // 处理冬灌数据
  getWinterMonthData(res) {
    if (res['period']) {
      const year = res['period']['y'];
      const stDate = res['period']['st_date'].split('-');
      const edDate = res['period']['ed_date'].split('-');
      const headThirdArr = this.dispatchService.getMngWinterThirdHead(stDate, edDate);
      this.dateHeadList = this.dispatchService.getMngWinterHead(stDate, edDate);
  } else {
      this.message.info('该管理处未配置冬灌信息！');
  }
  }

  // 处理月数据
  getMonthDetailData(res) {

  }

  // 处理旬数据
  getTenDaysDetailData(res) {

  }

  // 处理表格数据
  dealTableData(res) {
    this.colNameList = res['colNameList'];
    this.hwPlanData = res['hwPlanData'];
    const dropN = res.valList.length - this.dateHeadList.length;
    this.manageDataList = _.dropRight(res.manageDataList, dropN) ;
    this.argThreeYearsList = _.dropRight(res.argList, dropN) ;

    this.valList = [];
    const valList: Array<any> = _.dropRight(res.valList, dropN) ;
    valList.forEach(dayList => {
      const obj = {};
      const keyList = [];
      for (let i = 0; i < dayList.length; i++) {
        const key = 'val' + i;
        keyList.push(key);
        obj[key] = dayList[i];
      }
      obj['total'] = this.dispatchService.sumSltData(dayList);
      this.keyList = keyList;
      this.valList.push(obj);
    });
    this.updateEditCache(this.valList);
    this.calcTableData();
  }

  calcTableData() {
    this.colNameList.forEach((colObj, i) => {
      const key = 'val' + i;
      const mngData = this.util.getItemValues(this.valList, key, true);
      this.valTotalList[i] = this.dispatchService.keepTwoDecimalFull(this.util.sum(mngData), 1);
      this.waterTotalList[i] = this.dispatchService.keepTwoDecimalFull(this.dispatchService.getWaterByFlow(this.valTotalList[i]), 1);
      this.argDayList[i] = this.dispatchService.keepTwoDecimalFull((this.valTotalList[i] / this.dateHeadList.length), 1);
    });
    this.valList.forEach(dayList => {
      dayList['total'] = this.dispatchService.sumSltData(this.dispatchService.getValList(dayList));
    });
    const yearOnYearStr = (this.dispatchService.sumSltData(this.argDayList) - this.hwPlanData).toFixed(2);
    this.yearOnYear =  parseFloat(yearOnYearStr);
  }

  submitEvent(type = '') {
    const params = {
      reportId: '5',
      manageId: JSON.parse(localStorage.userInfo).manageId,
      y: this.paramsData.y,
      m: this.paramsData.m,
      dataType: this.paramsData.dataType,
      dataFlag: "",
      action: type ? type : "",
      data: ""
    };
    const data = [];
    this.colNameList.forEach((colObj, i) => {
      const key = 'val' + i;
      const mngData = this.util.getItemValues(this.valList, key, true);
      if (this.monthReportType === 'tenDays') {
        data.push({
          areaId: colObj.areaId,
          val: mngData
        });
      } else {
        const firstRow = _.slice(mngData, 0, 10);
        const secondRow = _.slice(mngData, 10, 20);
        data.push({
          areaId: colObj.areaId,
          val: firstRow
        });
        data.push({
          areaId: colObj.areaId,
          val: secondRow
        });
        let thirdRow = [];
        let fourthRow = [];
        if (this.monthReportType === 'winter') {
          thirdRow = _.slice(mngData, 20, 30);
          fourthRow =  _.slice(mngData, 30, mngData.length);
          data.push({
            areaId: colObj.areaId,
            val: thirdRow
          });
          data.push({
            areaId: colObj.areaId,
            val: fourthRow
          });
        } else {
          thirdRow = _.slice(mngData, 20, mngData.length);
          data.push({
            areaId: colObj.areaId,
            val: thirdRow
          });
        }
      }
    });
    params.data = JSON.stringify(data);
    this.fetchService.post<any>('plan/wrsReportData/add', params).subscribe(res => {
      const message = type ? '上传' : '保存';
      this.message.success(`${message}成功`);
  });
  }

  goBack(): void {
    this.router.navigate(['/dispatch-plan/slt-dispatch'], { skipLocationChange: true, queryParams: {selectedIndex: 1}});
  }

  isEditableTd(i): boolean {
    return this.currentIndex === i && this.editCache[i].edit;
  }

  startEdit(i: number, event: MouseEvent): void {
    event.preventDefault();
    event.stopPropagation();
    this.currentIndex = i;
    if (this.pageType === 'edit') {
      this.editCache[i].edit = true;
    }
    this.calcTableData();
  }

  updateEditCache(data): void {
    data.forEach((item, i) => {
        this.editCache[i] = {
            edit: false,
            data: { ...item }
        };
    });
  }
}
